package com.example.controller;

import com.example.pojo.User;
import com.example.service.UserService;
import com.example.utils.Result;
import com.example.pojo.Teacher;
import com.example.service.TeacherService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@Api(value = "教师管理接口")
public class TeacherController {
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private UserService userService;

    //添加
    @PostMapping("/teachers")
    public Result add(@RequestBody Teacher teacher){
        log.info("添加教师信息{}:"+ teacher);
        //添加教师信息
        teacherService.add(teacher);
        //创建用户对象
        User user = teacher.createUser();
        //添加用户信息
        userService.add(user);
        //关联两表
        try{
            teacherService.connectUser("林岭");
            log.info("关联成功");
        }catch (Exception e){
            log.info("关联失败");
            return Result.error("关联失败");
        }
        return Result.success();
    }

    //查询
    @GetMapping("/teachers")
    public Result list(){
        log.info("查询教师列表");
        List<Teacher> teacherList = teacherService.list();
        return Result.success(teacherList);
    }

    //根据id查询
    @GetMapping("/teachers/{id}")
    public Result Teacher(@PathVariable Integer id){
        log.info("查询教师{}:"+ id);
        Teacher teacher = teacherService.query(id);
        return Result.success(teacher);
    }

    //根据名字查询
    @GetMapping("/teachers/router")
    public Result Teacher(@RequestParam String teacherName){
        log.info("查询教师{}:"+ teacherName);
        Teacher teacher = teacherService.query(teacherName);
        return Result.success(teacher);
    }

    //修改
    @PutMapping("/teachers")
    public Result update(@RequestBody Teacher teacher){
        log.info("修改教师信息");
        teacherService.update(teacher);
        return Result.success();
    }

}
